/**
 * 下载文件
 * @param data
 * @param fileName
 */
export function downloadFile(data: Blob, fileName: string) {
  const label = document.createElement('a')
  label.href = window.URL.createObjectURL(data)
  label.download = fileName
  label.click()
  URL.revokeObjectURL(label.href)
}
interface IImageOptions {
  targetWidth?: number
  quality?: number
  outputFormat?: string
  maxSizeKB?: number
}
async function optimizedImageConverter(imageUrl: string, options: IImageOptions) {
  try {
    const {
      targetWidth = 100, // 目标宽度
      quality = 1, // JPEG质量 (0-1)
      outputFormat = 'image/jpeg', // 输出格式
      maxSizeKB = 100 // 最大体积限制
    } = options

    // 方案1：使用更高效的压缩方式
    const img = await loadImage(imageUrl)
    // 方案2：按比例缩小图片尺寸
    const { canvas, scale } = createScaledCanvas(img, targetWidth)

    // 方案3：质量压缩
    let base64String = await compressImage(canvas, quality, outputFormat)
    // 方案4：二次压缩检测
    if (getSizeKB(base64String) > maxSizeKB) {
      const adjustedQuality = quality * 0.8
      base64String = await compressImage(canvas, adjustedQuality, outputFormat)
    }
    const data = await convertToWebP(canvas, quality)
    // 方案5：WebP格式转换（需要浏览器支持）
    const base = `data:image/jpeg;base64,${data}`
    return base

    // return base64String
  } catch (error) {
    console.error('Image processing error:', error)
    throw error
  }
}

// 封装图片加载
function loadImage(url: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = url
  })
}

// 创建按比例缩放的Canvas
function createScaledCanvas(img: HTMLImageElement, targetWidth: number) {
  const scale = targetWidth / img.width
  const canvas = document.createElement('canvas')
  canvas.width = targetWidth
  canvas.height = img.height * scale

  const ctx = canvas.getContext('2d')
  ctx!.drawImage(img, 0, 0, canvas.width, canvas.height)
  return { canvas, scale }
}

// 压缩图片核心方法
async function compressImage(canvas: HTMLCanvasElement, quality: number, format: string): Promise<string> {
  return new Promise((resolve) => {
    canvas.toBlob(
      (blob) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve((reader.result as string)!.split(',')[1])
        reader.readAsDataURL(blob!)
      },
      format,
      quality
    )
  })
}

// 获取Base64体积（KB）
function getSizeKB(base64String: string) {
  return (base64String.length * 0.75) / 1024
}

// WebP转换（可选）
async function convertToWebP(canvas: HTMLCanvasElement, quality: number) {
  return new Promise((resolve) => {
    canvas.toBlob(
      (blob) => {
        const reader = new FileReader()
        reader.onloadend = () => resolve((reader.result as string)!.split(',')[1])
        reader.readAsDataURL(blob!)
      },
      'image/webp',
      quality
    )
  })
}

const getBase64ToImage = (base64: string) => {
  return `data:image/svg+xml,%3csvg width='32' height='32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3e %3cdefs%3e %3cclipPath id='b'%3e %3cpath d='M23.927 0a4 4 0 0 1 4 4v19.927a4 4 0 0 1-4 4h-5.212a4 4 0 0 0-3.255 1.675l-.899 1.259a1 1 0 0 1-1.627 0l-.899-1.259a4 4 0 0 0-3.255-1.675H4a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4h19.927Z'/%3e %3c/clipPath%3e %3cclipPath id='c'%3e %3cpath d='M21.6 0a4 4 0 0 1 4 4v17.6a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4h17.6Z'/%3e %3c/clipPath%3e %3cfilter id='a' x='-33.401%25' y='-30.55%25' filterUnits='userSpaceOnUse' width='144.534%25' height='140.734%25'%3e %3cfeGaussianBlur stdDeviation='2' in='SourceAlpha' result='i1'/%3e %3cfeOffset in='i1' result='i2'/%3e %3cfeColorMatrix values='0 0 0 0.0 0 0 0 0 0.0 0 0 0 0 0.0 0 0 0 0 0.5 0' in='i2'/%3e %3c/filter%3e %3cpattern id='image' x='0%25' y='0%25' height='100%25' width='100%25' viewBox='0 0 25.6 25.6'%3e %3cimage x='0%25' y='0%25' width='25.6' height='25.6' xlink:href='${base64}' preserveAspectRatio='xMidYMid slice'%3e %3c/image%3e %3c/pattern%3e %3c/defs%3e %3cpath d='M4 0h19.927a4 4 0 0 1 4 4v19.927a4 4 0 0 1-4 4h-5.212a4 4 0 0 0-3.255 1.675l-.899 1.259a1 1 0 0 1-1.627 0l-.899-1.259a4 4 0 0 0-3.255-1.675H4a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4Z' filter='url(%23a)' transform='translate(2)'/%3e %3cg clip-path='url(%23b)' transform='translate(2)'%3e %3cpath fill='%232D8CF0' d='M0 0h27.927v31.28H0V0z'/%3e %3c/g%3e %3cg clip-path='url(%23c)' transform='translate(3.164 1.164)'%3e %3cpath fill='url(%23image)' d='M0 0h25.6v25.6H0V0z'/%3e %3c/g%3e %3c/svg%3e
  
  `
}
export const getUrlToBase64 = async (url: string) => {
  const bas64 = await optimizedImageConverter(url, {
    targetWidth: 300,
    quality: 1,
  })
  return getBase64ToImage(bas64)
}
